package fileUtil

import (
	"bufio"
	"context"
	"crypto/md5"
	"fmt"
	"io"
	"io/fs"
	"os"
)

func CountFileMd5(ctx context.Context, filePath string) string {
	file, err := os.Open(filePath)
	if err != nil {
		return err.Error()
	}
	defer file.Close()
	md5h := md5.New()
	io.Copy(md5h, file)
	//fmt.Printf("%x", md5h.Sum([]byte("")))
	return fmt.Sprintf("%x", md5h.Sum([]byte("")))
}

func AeDataFileLog(ctx context.Context, filename string, fileext string, data []byte) {

	rootDir, _ := os.Getwd()
	separator := string(os.PathSeparator)
	dir := rootDir + separator + "myruntime" + separator
	ExistDir(dir)
	filePath := dir + filename + "." + fileext

	f, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
	}
	defer f.Close()

	writer := bufio.NewWriter(f)
	writer.WriteString(string(data))
	writer.Flush()

}

func ExistDir(path string) {
	// 判断路径是否存在
	_, err := os.ReadDir(path)
	if err != nil {
		// 不存在就创建
		err = os.MkdirAll(path, fs.ModePerm)
		if err != nil {
			fmt.Println(err)
		}
	}
}
